package main

// Connect to the XRPL Ledger using websocket and subscribe to an account
// translation from the JavaScript example to Go
// https://xrpl.org/monitor-incoming-payments-with-websocket.html
// This example uses the Gorilla websocket library to create a websocket client
// install: go get github.com/gorilla/websocket

import (
    "encoding/json"
    "flag"
    "log"
    "net/url"
    "os"
    "os/signal"
    "time"

    "github.com/gorilla/websocket"
)

// websocket address
var addr = flag.String("addr", "s.altnet.rippletest.net:51233", "http service address")

// Payload object
type message struct {
    Command  string   `json:"command"`
    Accounts []string `json:"accounts"`
}

func main() {
    flag.Parse()
    log.SetFlags(0)

    var m message

    // check for interrupts and cleanly close the connection
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    u := url.URL{Scheme: "ws", Host: *addr, Path: "/"}
    log.Printf("connecting to %s", u.String())

    // make the connection
    c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        panic(err)
    }
    // on exit close
    defer c.Close()

    done := make(chan struct{})

    // send a subscribe command and a target XRPL account
    m.Command = "subscribe"
    m.Accounts = append(m.Accounts, "rUCzEr6jrEyMpjhs4wSdQdz4g8Y382NxfM")

    // struct to JSON marshalling
    msg, _ := json.Marshal(m)
    // write to the websocket
    err = c.WriteMessage(websocket.TextMessage, []byte(string(msg)))
    if err != nil {
        panic(err)
    }

    // read from the websocket
    _, message, err := c.ReadMessage()
    if err != nil {
        panic(err)
    }
    // print the response from the XRP Ledger
    log.Printf("recv: %s", message)

    // handle interrupt
    for {
        select {
        case <-done:
            return
        case <-interrupt:
            log.Println("interrupt")

            // Cleanly close the connection by sending a close message and then
            // waiting (with timeout) for the server to close the connection.
            err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
            if err != nil {
                panic(err)
            }
            select {
            case <-done:
            case <-time.After(time.Second):
            }
            return
        }
    }
}
